package com.zhangli.media;

//import android.media.MediaPlayer;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import java.io.IOException;
import java.io.File;
import android.app.Service;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * Created by zhangli on 2017/8/12.
 */

public class MyAudioRecord extends Service{
    public static final String TAG = "MyAudioRecord";

    private MediaRecorder myAudioRecorder=null;

    public void stop()
    {
        if(myAudioRecorder!=null) {
            myAudioRecorder.stop();
            myAudioRecorder.release();
            myAudioRecorder =null;
        }
    }

    public boolean start(String outputFile)
    {
        if(myAudioRecorder != null)
            return true;
        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);

        myAudioRecorder.setOutputFile(outputFile);
        try {
            myAudioRecorder.prepare();
            myAudioRecorder.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            myAudioRecorder = null;
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(TAG, "in onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String name = intent.getStringExtra("Command");
        Log.w(TAG, "CMD:" + name);
        switch(name)
        {
            case "start":
                String path = intent.getStringExtra("path");
                start(path);
                break;
            default:
                stop();
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w(TAG, "in onDestroy");
    }
}
